package com.tanhua.server.service;

import cn.hutool.core.date.DateUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.template.AliyunOssTemplate;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Peachblossom;
import com.tanhua.domain.vo.PeachblossomVO;
import com.tanhua.dubbo.api.PeachblossomApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class PeachblossomService {
    @Autowired
    private AliyunOssTemplate ossTemplate;
    @Reference
    private PeachblossomApi peachblossomApi;
    @Autowired
    private FastFileStorageClient fdsClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private StringRedisTemplate redisTemplate;


    public ResponseEntity sendSound(MultipartFile soundFile) throws IOException {
        User user = UserHolder.getUser();
        //把语音上传到阿里云
//        String url = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());

        //2. 把语音文件上传到FastDFS，得到视频的访问路径
        String suffix = soundFile.getOriginalFilename().substring(soundFile.getOriginalFilename().lastIndexOf(".") + 1);
        StorePath storePath = fdsClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), suffix, null);
        String soundUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

        //更新到mongo数据库
        Peachblossom peachblossom = new Peachblossom();
        peachblossom.setId(new ObjectId());
        peachblossom.setUserId(user.getId());
        peachblossom.setSoundUrl(soundUrl);

        peachblossomApi.save(peachblossom);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity acceptSound() {
        User user = UserHolder.getUser();

        long nowDate = System.currentTimeMillis();
        long endTime = DateUtil.endOfDay(new Date()).getTime();
        long time = endTime - nowDate;

        String remainingTimes = redisTemplate.opsForValue().get("remainingTimes" + user.getId());
        if (remainingTimes == null) {
            redisTemplate.opsForValue().set("remainingTimes" + user.getId(), "9", time, TimeUnit.MILLISECONDS);
        } else {
            remainingTimes = String.valueOf(Integer.parseInt(remainingTimes) - 1);
            redisTemplate.opsForValue().set("remainingTimes" + user.getId(), remainingTimes, time, TimeUnit.MILLISECONDS);
        }
        List<Peachblossom> peachblossomList = peachblossomApi.findSoundList();

        Peachblossom peachblossom = peachblossomList.get(new Random().nextInt(peachblossomList.size()));

        PeachblossomVO vo = new PeachblossomVO();
        UserInfo userInfo = userInfoApi.findById(peachblossom.getUserId());
        BeanUtils.copyProperties(userInfo, vo);
        vo.setSoundUrl(peachblossom.getSoundUrl());
        vo.setId(Integer.parseInt(peachblossom.getUserId().toString()));

        remainingTimes = redisTemplate.opsForValue().get("remainingTimes" + user.getId());
        vo.setRemainingTimes(Integer.parseInt(remainingTimes));


        if (peachblossomList.size() > 1 && vo.getRemainingTimes() > 0) {
            peachblossomApi.removeThisSound(peachblossom);
        }
        return ResponseEntity.ok(vo);
    }
}
